package com.purong.purong.activity;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.bean.AreaBean;
import com.purong.purong.bean.AreaListBean;
import com.purong.purong.bean.TextItemBean;
import com.purong.purong.bean.UserHouseBean;
import com.purong.purong.toggle.ToggleButton;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.NumDecTextWatch;
import com.purong.purong.util.ZeroStartUnableTextWatch;
import com.purong.purong.widget.AreaSelectDialog;
import com.purong.purong.widget.TextChoseDialog;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zengwenjie on 2017/12/15.
 */
public class UserHouseAddActivity extends BaseActivity {
    private EditText addressEd,areaEd,priceEd,contactNumEd,ageEd,repayCountEd,monthRepayEd,restRepayEd,mortNameEd,mortMoneyEd;
    private TextView locationTv,typeTv,startTimeTv,endTimeTv;
    private Button confirm;
    private TextChoseDialog mTypeDialog;
    private TextItemBean typeBean;
    private List<TextItemBean> typeList=new ArrayList<>();
    private UserHouseBean houseBean;
    private boolean isMortTurnOn,isPledTurnOn;
    private ToggleButton mortStatusBtn,pledStatusBtn;
    private AreaBean mProvince, mCity, mArea;
    private AreaSelectDialog lodgDialog;
    @Override
    public void initBundle() {
        houseBean =(UserHouseBean)getIntent().getSerializableExtra("USER_HOUSE");
    }

    @Override
    public int getRootViewId() {
        return R.layout.activity_user_house_add;
    }

    @Override
    public void initView() {
        showBack();
        showTitle("房产信息");
        mortStatusBtn = (ToggleButton) findViewById(R.id.mortgage_status_btn);
        mortStatusBtn.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (on) {
                    isMortTurnOn =true;
                    findViewById(R.id.mortgage_lay).setVisibility(View.VISIBLE);
                } else {
                    isMortTurnOn =false;
                    findViewById(R.id.mortgage_lay).setVisibility(View.GONE);
                    repayCountEd.setText("");
                    monthRepayEd.setText("");
                    restRepayEd.setText("");
//                    mortNameEd.setText("");
//                    mortMoneyEd.setText("");
//                    startTimeTv.setText("请选择");
//                    startTimeTv.setTextColor(getResources().getColor(R.color.text_gray));
//                    endTimeTv.setText("请选择");
//                    endTimeTv.setTextColor(getResources().getColor(R.color.text_gray));

                }
            }
        });
        pledStatusBtn = (ToggleButton) findViewById(R.id.pledge_status_btn);
        pledStatusBtn.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (on) {
                    isPledTurnOn =true;
                    findViewById(R.id.pledge_lay).setVisibility(View.VISIBLE);
                } else {
                    isPledTurnOn =false;
                    findViewById(R.id.pledge_lay).setVisibility(View.GONE);
                    mortNameEd.setText("");
                    mortMoneyEd.setText("");
                    startTimeTv.setText("请选择");
                    startTimeTv.setTextColor(getResources().getColor(R.color.text_gray));
                    endTimeTv.setText("请选择");
                    endTimeTv.setTextColor(getResources().getColor(R.color.text_gray));

                }
            }
        });
        locationTv=(TextView)findViewById(R.id.location_tv);
        typeTv=(TextView)findViewById(R.id.type_tv);
        startTimeTv=(TextView)findViewById(R.id.start_time_tv);
        endTimeTv=(TextView)findViewById(R.id.end_time_tv);
        addressEd=(EditText) findViewById(R.id.address_ed);
        areaEd=(EditText) findViewById(R.id.area_ed);
        priceEd=(EditText) findViewById(R.id.price_ed);
        contactNumEd=(EditText) findViewById(R.id.contact_number_ed);
        ageEd=(EditText) findViewById(R.id.age_ed);
        repayCountEd=(EditText) findViewById(R.id.repay_count_ed);
        monthRepayEd=(EditText) findViewById(R.id.month_repay_ed);
        restRepayEd=(EditText) findViewById(R.id.rest_repay_ed);
        mortNameEd=(EditText) findViewById(R.id.mortgage_name_ed);
        mortMoneyEd=(EditText) findViewById(R.id.mortgage_money_ed);
        areaEd.addTextChangedListener(new NumDecTextWatch(areaEd));
        priceEd.addTextChangedListener(new NumDecTextWatch(priceEd));
        ageEd.addTextChangedListener(new ZeroStartUnableTextWatch(ageEd));
        repayCountEd.addTextChangedListener(new ZeroStartUnableTextWatch(repayCountEd));
        monthRepayEd.addTextChangedListener(new ZeroStartUnableTextWatch(monthRepayEd));
        restRepayEd.addTextChangedListener(new NumDecTextWatch(restRepayEd));
        mortMoneyEd.addTextChangedListener(new NumDecTextWatch(mortMoneyEd));
        confirm=(Button)findViewById(R.id.confirm);
        if (houseBean ==null){
            confirm.setText("保存，进入下一房产");
        }else {
            confirm.setText("保存");
        }

    }
    private void setData(){
        if (houseBean ==null)
            return;
        if (houseBean.getProvince_id()!=null&&!houseBean.getProvince_id().equals("")
                &&houseBean.getCity_id()!=null&&!houseBean.getCity_id().equals("")
                &&houseBean.getArea_id()!=null&&!houseBean.getArea_id().equals("")){
            mProvince=new AreaBean();
            mProvince.setArea_id(houseBean.getProvince_id());
            mProvince.setAcronym(houseBean.getProvince_name());
            mCity=new AreaBean();
            mCity.setArea_id(houseBean.getCity_id());
            mCity.setAcronym(houseBean.getCity_name());
            mArea=new AreaBean();
            mArea.setArea_id(houseBean.getArea_id());
            mArea.setAcronym(houseBean.getArea_name());
            locationTv.setText(mProvince.getAcronym() +" "+ mCity.getAcronym() +" "+ mArea.getAcronym());
            locationTv.setTextColor(getResources().getColor(R.color.blue));
        }
        if (houseBean.getAddress()!=null){
            addressEd.setText(houseBean.getAddress());
        }
        if (houseBean.getArea()!=null){
            areaEd.setText(houseBean.getArea());
        }
        if (houseBean.getPrice()!=null){
            priceEd.setText(houseBean.getPrice());
        }
        if (houseBean.getContact_number()!=null){
            contactNumEd.setText(houseBean.getContact_number());
        }
        if (houseBean.getAge()!=null){
            ageEd.setText(houseBean.getAge());
        }
        if (houseBean.getHouse_type()!=null){
            switch (houseBean.getHouse_type()){
                case "1":
                    typeTv.setText("未知");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("1");
                    typeBean.setName("未知");
                    break;
                case "2":
                    typeTv.setText("小产权房");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("2");
                    typeBean.setName("小产权房");
                    break;
                case "3":
                    typeTv.setText("经济/限价房");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("3");
                    typeBean.setName("经济/限价房");
                    break;
                case "4":
                    typeTv.setText("房改/危改房");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("4");
                    typeBean.setName("房改/危改房");
                    break;
                case "5":
                    typeTv.setText("商铺");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("5");
                    typeBean.setName("商铺");
                    break;
                case "6":
                    typeTv.setText("厂房");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("6");
                    typeBean.setName("厂房");
                    break;
                case "7":
                    typeTv.setText("商住两用房");
                    typeTv.setTextColor(getResources().getColor(R.color.blue));
                    typeBean=new TextItemBean();
                    typeBean.setId("7");
                    typeBean.setName("商住两用房");
                    break;
            }
        }

        if (houseBean.getRepay_count()!=null&&!houseBean.getRepay_count().equals("")){
            repayCountEd.setText(houseBean.getRepay_count());
            isMortTurnOn =true;
        }
        if (houseBean.getMonth_repay()!=null&&!houseBean.getMonth_repay().equals("")){
            monthRepayEd.setText(houseBean.getMonth_repay());
            isMortTurnOn =true;
        }
        if (houseBean.getRest_repay()!=null&&!houseBean.getRest_repay().equals("")){
            restRepayEd.setText(houseBean.getRest_repay());
            isMortTurnOn =true;
        }
        if (houseBean.getMortgage_name()!=null&&!houseBean.getMortgage_name().equals("")){
            mortNameEd.setText(houseBean.getMortgage_name());
            isPledTurnOn =true;
        }
        if (houseBean.getStart_time()!=null&&!houseBean.getStart_time().equals("")){
            startTimeTv.setText(houseBean.getStart_time());
            startTimeTv.setTextColor(getResources().getColor(R.color.blue));
            isPledTurnOn =true;
        }
        if (houseBean.getEnd_time()!=null&&!houseBean.getEnd_time().equals("")){
            endTimeTv.setText(houseBean.getEnd_time());
            endTimeTv.setTextColor(getResources().getColor(R.color.blue));
            isPledTurnOn =true;
        }
        if (houseBean.getMortgage_money()!=null&&!houseBean.getMortgage_money().equals("")){
            mortMoneyEd.setText(houseBean.getMortgage_money());
            isPledTurnOn =true;
        }
        if (isMortTurnOn){
            findViewById(R.id.mortgage_lay).setVisibility(View.VISIBLE);
            mortStatusBtn.toggleOn();
        }else {
            findViewById(R.id.mortgage_lay).setVisibility(View.GONE);
            mortStatusBtn.toggleOff();
        }
        if (isPledTurnOn){
            findViewById(R.id.pledge_lay).setVisibility(View.VISIBLE);
            pledStatusBtn.toggleOn();
        }else {
            findViewById(R.id.pledge_lay).setVisibility(View.GONE);
            pledStatusBtn.toggleOff();
        }
    }

    private void addHouse(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (mProvince==null||mCity==null||mArea==null){
            showToast("房产地址为必选项");
            return;
        }else {
            params.put("province_id",mProvince.getArea_id());
            params.put("city_id",mCity.getArea_id());
            params.put("area_id",mArea.getArea_id());
        }
        if (addressEd.getText().toString().trim().equals("")){
            showToast("详细地址为必填项");
            return;
        }else {
            params.put("address",addressEd.getText().toString().trim());
        }
        if (areaEd.getText().toString().trim().equals("")){
            showToast("房产面积为必填项");
            return;
        }else {
            params.put("area",areaEd.getText().toString().trim());
        }
        params.put("price",priceEd.getText().toString().trim());
        if (contactNumEd.getText().toString().trim().equals("")){
            showToast("房产证编号为必填项");
            return;
        }else {
            params.put("contact_number",contactNumEd.getText().toString().trim());
        }
        if (ageEd.getText().toString().trim().equals("")){
            showToast("房龄为必填项");
            return;
        }else {
            params.put("age",ageEd.getText().toString().trim());
        }
        if (typeBean==null){
            showToast("房产类型为必选项");
            return;
        }else {
            params.put("house_type",typeBean.getId());
        }
        if (isMortTurnOn){
            params.put("repay_count",repayCountEd.getText().toString().trim());
            params.put("month_repay",monthRepayEd.getText().toString().trim());
            params.put("rest_repay",restRepayEd.getText().toString().trim());
        }else {
            params.put("repay_count","");
            params.put("month_repay","");
            params.put("rest_repay","");
        }
        if (isPledTurnOn){
            params.put("mortgage_name",mortNameEd.getText().toString().trim());
            params.put("mortgage_money",mortMoneyEd.getText().toString().trim());
            if (!startTimeTv.getText().toString().trim().equals("请选择")){
                params.put("start_time",startTimeTv.getText().toString().trim());
            }else {
                params.put("start_time","");
            }
            if (!endTimeTv.getText().toString().trim().equals("请选择")){
                params.put("end_time",endTimeTv.getText().toString().trim());
            }else {
                params.put("end_time","");
            }
        }else {
            params.put("mortgage_name","");
            params.put("mortgage_money","");
            params.put("start_time","");
            params.put("end_time","");
        }
        request(Contant.HOUSE_ADD,params,true,true);
    }
    private void editHouse(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("user_house_id", houseBean.getUser_house_id());
        if (mProvince==null||mCity==null||mArea==null){
            showToast("房产地址为必选项");
            return;
        }else {
            params.put("province_id",mProvince.getArea_id());
            params.put("city_id",mCity.getArea_id());
            params.put("area_id",mArea.getArea_id());
        }
        if (addressEd.getText().toString().trim().equals("")){
            showToast("详细地址为必填项");
            return;
        }else {
            params.put("address",addressEd.getText().toString().trim());
        }
        if (areaEd.getText().toString().trim().equals("")){
            showToast("房产面积为必填项");
            return;
        }else {
            params.put("area",areaEd.getText().toString().trim());
        }
        params.put("price",priceEd.getText().toString().trim());
        if (contactNumEd.getText().toString().trim().equals("")){
            showToast("房产证编号为必填项");
            return;
        }else {
            params.put("contact_number",contactNumEd.getText().toString().trim());
        }
        if (ageEd.getText().toString().trim().equals("")){
            showToast("房龄为必填项");
            return;
        }else {
            params.put("age",ageEd.getText().toString().trim());
        }
        if (typeBean==null){
            showToast("房产类型为必选项");
            return;
        }else {
            params.put("house_type",typeBean.getId());
        }
        if (isMortTurnOn){
            params.put("repay_count",repayCountEd.getText().toString().trim());
            params.put("month_repay",monthRepayEd.getText().toString().trim());
            params.put("rest_repay",restRepayEd.getText().toString().trim());
        }else {
            params.put("repay_count","");
            params.put("month_repay","");
            params.put("rest_repay","");
        }
        if (isPledTurnOn){
            params.put("mortgage_name",mortNameEd.getText().toString().trim());
            params.put("mortgage_money",mortMoneyEd.getText().toString().trim());
            if (!startTimeTv.getText().toString().trim().equals("请选择")){
                params.put("start_time",startTimeTv.getText().toString().trim());
            }else {
                params.put("start_time","");
            }
            if (!endTimeTv.getText().toString().trim().equals("请选择")){
                params.put("end_time",endTimeTv.getText().toString().trim());
            }else {
                params.put("end_time","");
            }
        }else {
            params.put("mortgage_name","");
            params.put("mortgage_money","");
            params.put("start_time","");
            params.put("end_time","");
        }
        request(Contant.HOUSE_EDIT,params,true,true);
    }
    private void initArea(String parentId) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("parent_id", parentId);
        request(Contant.AREA, params, true);
    }
    private void initTypeDialog(){
        mTypeDialog=new TextChoseDialog(this);
        mTypeDialog.setOnTextChoseListener(new TextChoseDialog.OnTextChoseListener() {
            @Override
            public void onChose(int position, TextItemBean item) {
                typeBean=item;
                typeTv.setText(typeBean.getName());
                typeTv.setTextColor(getResources().getColor(R.color.blue));

            }

        });
        TextItemBean itemBean=new TextItemBean();
        itemBean.setId("1");
        itemBean.setName("未知");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("2");
        itemBean.setName("小产权房");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("3");
        itemBean.setName("经济/限价房");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("4");
        itemBean.setName("房改/危改房");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("5");
        itemBean.setName("商铺");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("6");
        itemBean.setName("厂房");
        typeList.add(itemBean);
        itemBean=new TextItemBean();
        itemBean.setId("7");
        itemBean.setName("商住两用房");
        typeList.add(itemBean);
        mTypeDialog.setData(typeList);
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.AREA)) {
            if (responseInfo.isRequestOk) {
                try{
                    AreaListBean bean = JSON.parseObject(responseInfo.content, AreaListBean.class);
                    if (lodgDialog != null)
                        lodgDialog.setData(bean.getArea_list());
                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.HOUSE_ADD)){
            if (responseInfo.isRequestOk){
                showToast("添加成功");
                Intent intent=new Intent(this,UserHouseAddActivity.class);
                startActivity(intent);
                this.finish();
            }
        }else if (responseInfo.url.equals(Contant.HOUSE_EDIT)){
            if (responseInfo.isRequestOk){
                showToast("编辑成功");
                this.finish();
            }
        }
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.confirm:
                if (houseBean !=null){
                    editHouse();
                }else {
                    addHouse();
                }
                break;
            case R.id.type_lay:
                if (mTypeDialog==null){
                    initTypeDialog();
                }
                mTypeDialog.show();
                break;

            case R.id.start_time_lay:
                TimePickerView startTime;
                startTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
                //控制时间范围
                Calendar buyCalendar = Calendar.getInstance();
                startTime.setRange(1900, buyCalendar.get(Calendar.YEAR));

                if (startTimeTv.getText().equals("请选择")) {
                    startTime.setTime(new Date());
                } else {
                    startTime.setTime(CommonUtil.Date2Millis(startTimeTv.getText().toString()));
                }
                startTime.setCyclic(true);
                startTime.setCancelable(true);
                //时间选择后回调
                startTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

                    @Override
                    public void onTimeSelect(Date date) {
                        startTimeTv.setText(CommonUtil.DateFormat(date));
                        startTimeTv.setTextColor(getResources().getColor(R.color.blue));
                    }
                });
                startTime.show();
                break;
            case R.id.end_time_lay:
                TimePickerView endTime;
                endTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
                //控制时间范围
                Calendar repayCalendar = Calendar.getInstance();
                endTime.setRange(1900, repayCalendar.get(Calendar.YEAR));

                if (endTimeTv.getText().equals("请选择")) {
                    endTime.setTime(new Date());
                } else {
                    endTime.setTime(CommonUtil.Date2Millis(endTimeTv.getText().toString()));
                }
                endTime.setCyclic(true);
                endTime.setCancelable(true);
                //时间选择后回调
                endTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

                    @Override
                    public void onTimeSelect(Date date) {
                        endTimeTv.setText(CommonUtil.DateFormat(date));
                        endTimeTv.setTextColor(getResources().getColor(R.color.blue));
                    }
                });
                endTime.show();
                break;
            case R.id.location_lay:
                lodgDialog = new AreaSelectDialog(this, mProvince, mCity,mArea , new AreaSelectDialog.OnAreaClickListener() {
                    @Override
                    public void onLoadArea(String parentId) {
                        lodgDialog.setData(null);
                        initArea(parentId);
                    }

                    @Override
                    public void onResult(AreaBean province, AreaBean city, AreaBean distric) {
                        mProvince=province;
                        mCity=city;
                        mArea=distric;
                        locationTv.setText(mProvince.getAcronym()+" " + mCity.getAcronym() +" "+ mArea.getAcronym());
                        locationTv.setTextColor(getResources().getColor(R.color.blue));
                    }

                });

                lodgDialog.show();
                break;
        }
    }
    @Override
    public void initData() {
        if(houseBean !=null){
            setData();
        }
    }
}
